﻿using BLL;
using DBUtility;
using Model;
using Models;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Threading;
using System.Windows.Forms;

namespace ZJUploadTool
{
    public partial class frmMain : Form
    {
        private Thread thFresh;

        public frmMain()
        {            
            InitializeComponent();
            timer1.Interval = 60000 * 120;
            timer1.Enabled = true;
            timer1.Start();
            timer1.Tick += new EventHandler(GetAccessToken);
            this.GetAccessToken(null, null);
        }

        private void BindDatas()
        {
            while (true)
            {
                Thread.Sleep(3000);

                string strSql = "select top 100 a.JCLSH,a.JCCS,a.HPHM,a.ZJLSH,a.VIN,b.UPLAOD_ZJ,a.ZJLWZT from VEHICLE_DISPATCH a left join RESULT_VEHICLE_STATUS b on  a.JCLSH=b.JCLSH";
                strSql += " where (b.UPLAOD_ZJ is null or UPLAOD_ZJ<>'1')";
                strSql += " and a.ZJLWZT<>'3' ";
                strSql += " and JCZL like '%Z%' and a.HPZLDH<>'15'";
                strSql += "  order by a.ID desc";

                DataTable dt = new DataTable();
                DbHelper.GetTable(strSql, ref dt);

                Action action = () =>
                {
                    dgItems.DataSource = dt;
                    dgItems.AutoGenerateColumns = false;
                    dgItems.Columns[0].MinimumWidth = 180;
                    dgItems.Columns[1].MinimumWidth = 130;
                    dgItems.Columns[2].MinimumWidth = 150;
                    dgItems.Columns[3].MinimumWidth = 120;
                    dgItems.Columns[4].MinimumWidth = 120;
                    dgItems.Columns[5].MinimumWidth = 240;
                    dgItems.Columns[6].MinimumWidth = 130;
                };

                this.Invoke(action);
            }
        }

        private void BindDatas(string strHPHM)
        {
            dgItems.DataSource = null;
            string strSql = "select top 100 a.JCLSH,a.JCCS,a.HPHM,a.ZJLSH,a.VIN,b.UPLAOD_ZJ,a.ZJLWZT from VEHICLE_DISPATCH a left join RESULT_VEHICLE_STATUS b on  a.JCLSH=b.JCLSH";
            strSql += " where a.HPHM like '%" + strHPHM + "%'";
            strSql += " and JCZL like '%Z%' and a.HPZLDH<>'15'";
            strSql += "  order by a.ID desc";

            DataTable dt = new DataTable();
            DbHelper.GetTable(strSql, ref dt);
            dgItems.DataSource = dt;
            dgItems.AutoGenerateColumns = false;

            dgItems.Columns[0].MinimumWidth = 180;
            dgItems.Columns[1].MinimumWidth = 130;
            dgItems.Columns[2].MinimumWidth = 150;
            dgItems.Columns[3].MinimumWidth = 120;
            dgItems.Columns[4].MinimumWidth = 220;
            dgItems.Columns[5].MinimumWidth = 80;
            dgItems.Columns[6].MinimumWidth = 130;
        }

        private void frmMain_FormClosed(object sender, FormClosedEventArgs e)
        {

        }

        private void dgItems_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0)
            {
                string strJCLSH = dgItems.Rows[e.RowIndex].Cells[0].Value.ToString();
                FrmUpload frmUpload = new FrmUpload(strJCLSH);
                frmUpload.ShowDialog();
            }
        }

        #region share Vehicle Info 
        private void ShareVehicleInfo(VEHICLE_DISPATCH vehicleDispatch,
                                      LOGIN_VEHICLE_INFO loginVehicleInfo)
        {
            Models.VehicleInfoEntity vehicleInfoEntity = new Models.VehicleInfoEntity();
            vehicleInfoEntity.dsId = UploadConfig.GetConfig().stationID;
            vehicleInfoEntity.vehicleNo = vehicleDispatch.HPHM;
            vehicleInfoEntity.vehicleBodyColor = ChangeTo_Net_HPYS(loginVehicleInfo.CSYS);
            vehicleInfoEntity.plateColorCode = loginVehicleInfo.HPYSDH;
            vehicleInfoEntity.vinNo = loginVehicleInfo.VIN;
            vehicleInfoEntity.vehicleBrandModel = loginVehicleInfo.PPXH;
            vehicleInfoEntity.registDate = loginVehicleInfo.CCDJRQ;
            vehicleInfoEntity.vehicleType = loginVehicleInfo.CLZLDH;
            vehicleInfoEntity.overallSize = string.Format("{0}mm×{1}mm×{2}mm",
                                            loginVehicleInfo.CSC,
                                            loginVehicleInfo.CSK,
                                            loginVehicleInfo.CSG);
            vehicleInfoEntity.axleAmount = loginVehicleInfo.ZZS;
            vehicleInfoEntity.steeringAxleAmount = "";
            vehicleInfoEntity.vehicleWeight = loginVehicleInfo.ZBZL;
            vehicleInfoEntity.approveWeight = loginVehicleInfo.HDZH;
            vehicleInfoEntity.totalWeight = loginVehicleInfo.ZZL;
            vehicleInfoEntity.owwnerName = loginVehicleInfo.SYR;
            //---->following field is NOT neccessery<----//
            vehicleInfoEntity.trailerVehicleNo = loginVehicleInfo.GLCHPHM;
            vehicleInfoEntity.transCertificateCode = loginVehicleInfo.YYZH;
            vehicleInfoEntity.transCertificateFirstDate = "";
            vehicleInfoEntity.engineNo = loginVehicleInfo.FDJH;
            vehicleInfoEntity.engineModel = loginVehicleInfo.FDJXH;
            vehicleInfoEntity.chassisNo = "";
            vehicleInfoEntity.productionDate = "";
            vehicleInfoEntity.busTypeLevel = loginVehicleInfo.KCLXDJDH;
            vehicleInfoEntity.brakeModele = "";
            vehicleInfoEntity.parkType = "";
            vehicleInfoEntity.parkAxle = loginVehicleInfo.ZCZWZ;
            vehicleInfoEntity.driveType = loginVehicleInfo.QDXSDH;
            vehicleInfoEntity.driveAxleAmount = "";
            vehicleInfoEntity.fuelType = loginVehicleInfo.RLLBDH;
            vehicleInfoEntity.lampSystem = loginVehicleInfo.QZDZ;
            vehicleInfoEntity.vehicleSuspensionForm = "";
            vehicleInfoEntity.ratifiedLoadCapacity = loginVehicleInfo.CYS;
            vehicleInfoEntity.seatCount = loginVehicleInfo.CYS;
            vehicleInfoEntity.travelMileage = loginVehicleInfo.LJXSLC;
            vehicleInfoEntity.farLightCanAdjust = loginVehicleInfo.YGGSNFKTDH;
            vehicleInfoEntity.parkAxle = "";
            vehicleInfoEntity.maxDesignSpeed = loginVehicleInfo.ZGSJCS;
            vehicleInfoEntity.isTurbo = "";
            vehicleInfoEntity.isAbs = "";
            vehicleInfoEntity.engineCylinder = loginVehicleInfo.FDJGS;

            string vehicleInfoJson = ExtendMethod.javaScriptSerializer.Serialize(vehicleInfoEntity);
            string requestResultJson = ZJNet.ZJSendMsg(vehicleInfoJson,
                                                       UploadConfig.GetConfig().url,
                                                       ExtendMethod.GetJson(vehicleInfoJson,
                                                       IPCTypeConfig.GetUploadMethod(
                                                       IPCTypeConfig.IPCType.UPLOAD_VEHICLE_INFO,
                                                       UploadConfig.GetConfig().accessToken)));
        }
        #endregion

        #region Get Access Token
        private void GetAccessToken(object sender,EventArgs e)
        {
            Models.getAccessToken requestBody = new Models.getAccessToken();
            Dictionary<string, string> jsonKeyValueSet = new Dictionary<string, string>();
            jsonKeyValueSet.Add("username", requestBody.username);
            jsonKeyValueSet.Add("password", requestBody.password);
            string requestResultJson = ZJNet.ZJSendMsg(
                ExtendMethod.GetJsonEx(jsonKeyValueSet,"getAccessToken"),
                UploadConfig.GetConfig().url,
                "get_access_token");
            Models.getAccessTokenResult requestResultEntity
                = ExtendMethod
                .javaScriptSerializer
                .Deserialize<Models.getAccessTokenResult>(requestResultJson);
            UploadConfig.GetConfig().accessToken = requestResultEntity.access_token;
        }
        #endregion

        #region Get Vehicle Info And DetectSn
        private getVehicleInfoAndDetectSnResult GetVehicleInfoAndDetectSn(get_vehicle_info_para vehicleInfoEntity)
        {
            Dictionary<string, string> dicIPCTypeValue = new Dictionary<string, string>();
            string szVehicleInfoJson = ExtendMethod.javaScriptSerializer.Serialize(vehicleInfoEntity);
            string szGetVehicleInfoAndDetectSnJson 
                = ExtendMethod.GetJson(szVehicleInfoJson, "getVehicleInfoAndDetectSn");
            string szRequestResultJson =
                ZJNet.ZJSendMsg(szGetVehicleInfoAndDetectSnJson,
                UploadConfig.GetConfig().url,
                IPCTypeConfig.GetUploadMethod(
                IPCTypeConfig.IPCType.GET_DETECT_SN,
                UploadConfig.GetConfig().accessToken));
            getVehicleInfoAndDetectSnResult requestResultEntity =
                ExtendMethod.javaScriptSerializer
                .Deserialize<getVehicleInfoAndDetectSnResult>(szRequestResultJson);

            return requestResultEntity;
        }
        #endregion

        #region 湖北
        private void GetSn(LOGIN_VEHICLE_INFO vehicleEntity)
        {
            ZJNet zjNet = new ZJNet();
            get_vehicle_info_para para = new get_vehicle_info_para();
            para.dsId = "";
            para.vehicleNo = vehicleEntity.HPHM;
            para.plateColorCode = ChangeTo_Net_HPYS(vehicleEntity.HPYS);
            string strSendJson = JsonConvert.SerializeObject(para);
            string strResultJson = zjNet.ZJSendMsg(strSendJson, "get_vehicle_info_and_detect_sn");            
        }

        private void UploadMsg(VEHICLE_DISPATCH dispatchEntity, LOGIN_VEHICLE_INFO vehicleEntity)
        {
            ZJNet zjNet = new ZJNet();
            upload_vehicle_info_para para = new upload_vehicle_info_para();
            para.dsId = UploadConfig.GetConfig().stationID;
            para.vehicleNo = vehicleEntity.HPHM;
            para.plateColorCode = ChangeTo_Net_HPYS(vehicleEntity.HPYS);
            para.vinNo = vehicleEntity.VIN;
            para.ownerName = vehicleEntity.SYR;
            para.vehicleBodyColor = vehicleEntity.CSYS;
            para.trailerVehicleNo = "";   //挂车牌照号
            para.vehicleBrandModel = vehicleEntity.PPXH;
            para.transCertificateCode = vehicleEntity.YYZH;
            para.engineNo = vehicleEntity.FDJH;
            para.engineModel = vehicleEntity.FDJXH;
            para.chassisNo = vehicleEntity.DPXH;
            para.productionDate = vehicleEntity.CCRQ;
            para.registDate = vehicleEntity.CCDJRQ;
            para.vehicleType = vehicleEntity.CLZLDH;
            para.busTypeLevel = vehicleEntity.KCLXDJDH;
            para.newOldExtent = "";
            para.brakeModel = vehicleEntity.ZDFSDH;
            para.parkType = "";
            para.driveType = "";
            para.overallSize = string.Format("{0}mm×{1}mm×{2}mm", vehicleEntity.CSC, vehicleEntity.CSK, vehicleEntity.CSG);
            para.axleAmount = vehicleEntity.ZZS;
            para.steeringAxleAmount = "";
            para.driveAxleAmount = "";
            para.fuelType = vehicleEntity.RLLBDH;
            para.lampSystem = vehicleEntity.QZDZDH;
            para.vehicleSuspensionForm = vehicleEntity.ZXZXJXSDH;
            para.vehicleWeight = vehicleEntity.ZBZL;
            para.approveWeight = vehicleEntity.HDZH;
            para.totalWeight = vehicleEntity.ZZL;
            para.ratifiedLoadCapacity = "";
            para.seatCount = "";
            para.travelMileage = vehicleEntity.LJXSLC;
            para.farLightCanAdjust = vehicleEntity.YGGSNFKT;
            para.parkAxle = vehicleEntity.ZCZWZ;
            para.maxDesignSpeed = "";
            para.isTurbo = "";
            para.isAbs = "";
            para.engineCylinderNumber = "";
            string strSendJson = JsonConvert.SerializeObject(para);
            zjNet.ZJSendMsg(strSendJson, "upload_vehicle_info");

        }

        private string ChangeTo_Net_HPYS(string strCSYS)
        {
            string strResult = "1";
            switch (strCSYS)
            {
                case "蓝":
                    strResult = "1";
                    break;
                case "黄":
                    strResult = "2";
                    break;
                case "黑":
                    strResult = "3";
                    break;
                case "白":
                    strResult = "4";
                    break;
                case "绿":
                    strResult = "5";
                    break;
                case "黄绿":
                    strResult = "6";
                    break;
                case "农黄":
                    strResult = "8";
                    break;
                case "其他":
                    strResult = "9";
                    break;
                    
            }
            return strResult;
        }     
        #endregion

        #region 按钮事件
        private void btnStop_Click(object sender, EventArgs e)
        {
            btnStart.Enabled = true;
            if (thFresh != null)
            {
                thFresh.Abort();
                thFresh = null;
            }
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            string strHPHM = txtHPHM.Text.Trim();
            BindDatas(strHPHM);
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (dgItems.SelectedCells.Count != 0)
            {
                //得到选中行的索引
                int intRow = dgItems.SelectedCells[0].RowIndex;

                if (MessageBox.Show("您确定要删除本条记录吗？", "信息提示", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
                {
                    string strJCLSH = dgItems.SelectedCells[0].Value.ToString();

                    VEHICLE_DISPATCH_BLL Dis_bll = new VEHICLE_DISPATCH_BLL();
                    var vModel = Dis_bll.GetModel(strJCLSH);

                    vModel.ZJLWZT = "3";

                    bool bRet = Dis_bll.Update(vModel, strJCLSH);
                    if (bRet)
                    {
                        dgItems.Rows.RemoveAt(intRow);
                        MessageBox.Show("删除成功！");
                    }
                }
            }
        }

        private void btnLogin_Click(object sender, EventArgs e)
        {
            try
            {
                if (dgItems.SelectedCells.Count != 0)
                {
                    //得到选中行的索引
                    int intRow = dgItems.SelectedCells[0].RowIndex;
                    string strJCLSH = dgItems.Rows[intRow].Cells[0].Value.ToString();
                    string strHPHM = dgItems.Rows[intRow].Cells[3].Value.ToString();

                    VEHICLE_DISPATCH_BLL bllVehicleDispatch = new VEHICLE_DISPATCH_BLL();
                    var vModel = bllVehicleDispatch.GetModel(strJCLSH);

                    LOGIN_VEHICLE_INFO_BLL bllLoginVehicleInfo = new LOGIN_VEHICLE_INFO_BLL();
                    LOGIN_VEHICLE_INFO[] infos = bllLoginVehicleInfo.GetModelList(string.Format("VIN ='{0}'", vModel.VIN));
                    if (infos.Length > 0)
                    {
                        vModel.ZJLWZT = "0";
                        bool bRet = bllVehicleDispatch.Update(vModel, strJCLSH);
                        if (bRet)
                        {                            
                            //UploadMsg(vModel,infos[0]);
                            //GetSn(infos[0]);
                            var loginVehicleInfo = infos[0];
                            get_vehicle_info_para getVehicleInfoEntity = new get_vehicle_info_para();
                            getVehicleInfoEntity.dsId = UploadConfig.GetConfig().stationID;
                            getVehicleInfoEntity.plateColorCode = ChangeTo_Net_HPYS(loginVehicleInfo.HPYS);
                            getVehicleInfoEntity.vehicleNo = loginVehicleInfo.HPHM;
                            getVehicleInfoEntity.vinNo = loginVehicleInfo.VIN;
                            getVehicleInfoAndDetectSnResult requestResultEntity = GetVehicleInfoAndDetectSn(getVehicleInfoEntity);
                            string _ZJLSH = ExtendMethod.javaScriptSerializer
                                                    .Deserialize<data>(requestResultEntity.data)
                                                    .detectSn;
                            loginVehicleInfo.ZJLSH = _ZJLSH;
                            vModel.ZJLSH = _ZJLSH;
                            if(bllVehicleDispatch.Update(vModel, strJCLSH) &&
                            bllLoginVehicleInfo.Update(loginVehicleInfo, loginVehicleInfo.ID))
                            {
                                MessageBox.Show("登陸成功.");
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("登录失败！" + ex.Message);
            }
        }

        private void btnInit_Click(object sender, EventArgs e)
        {

        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            btnStart.Enabled = false;
            if (thFresh == null)
            {
                thFresh = new Thread(BindDatas);
                thFresh.IsBackground = true;
                thFresh.Start();
            }
        }
        #endregion      
        private void button1_Click(object sender, EventArgs e)
        {
            Dictionary<string, object> detectionStation = new Dictionary<string, object>();
            var stationInfo = new
            {
                dsId = UploadConfig.GetConfig().stationID,
                dsName = UploadConfig.GetConfig().stationName,
                dsType = "170",
                createStationDate = "20031101",
                orgnumber = "916229000672243837",
                ma = "182805020727",
                maExpDate = "20240326",
                orgId = "622900",
                createDate = "20181119"
            };
            var detectStation = new { stationInfo = stationInfo };
            detectionStation.Add("detectionStation", detectStation);
            string detectionStationInfoJson = Newtonsoft.Json.JsonConvert.SerializeObject(detectionStation);
            string requestResult = ZJNet.ZJSendMsg(
            ExtendMethod.GetJson(detectionStationInfoJson, "shareDetectionStationInfo"),
            UploadConfig.GetConfig().url,
            IPCTypeConfig.GetUploadMethod(IPCTypeConfig.IPCType.UPLOAD_STATION_INFO,
            UploadConfig.GetConfig().accessToken));
            MessageBox.Show(requestResult);
        }
    }
}
